import datetime
import re
import subprocess


def fetch_git_commit_sha_datetime(git_commit):
  if git_commit == 'HEAD':
    git_commit_sha = subprocess.check_output(['git', 'rev-parse', 'HEAD']).strip().decode()
  else:
    pattern = re.compile(r'\b[0-9a-f]{40}\b')
    match = pattern.match(git_commit)
    if not match:
      raise ValueError(git_commit)
    else:
      git_commit_sha = git_commit

  git_commit_datetime_cmd = "TZ=UTC git show --quiet --date=local --format='%cd'"
  git_commit_datetime_str = subprocess.check_output(git_commit_datetime_cmd,
                                                    shell=True).strip().decode()
  git_commit_datetime = datetime.datetime.strptime(git_commit_datetime_str, '%a %b %d %H:%M:%S %Y')
  return git_commit_datetime, git_commit_sha
